#include "crsf.h"
#include "usart.h"
extern uint8_t sport_or_crsf_flag;
uint8_t calcCRC(uint8_t *data, uint8_t len) {
    uint8_t crc = 0;
    for (uint8_t i = 0; i < len; i++) {
        crc ^= data[i];
        for (uint8_t j = 0; j < 8; j++) {
            if (crc & 0x80)
                crc = (crc << 1) ^ 0xD5;
            else
                crc = crc << 1;
        } 
    }
    return crc;
}
		
void sendCRSFFrame(uint8_t *sportData) {
		uint8_t crsfData[CRSF_FRAME_SIZE];
		memcpy(&crsfData,sportData,25);
		if(sport_or_crsf_flag)
		{
				crsfData[0] = CRSF_ADDRESS_FLIGHT_CONTROLLER; 
				crsfData[1] = 24; 
				crsfData[2] = CRSF_FRAMETYPE_RC_CHANNELS_PACKED;
		}else if(!sport_or_crsf_flag){
				crsfData[0] = SPORT_ADDRESS_FLIGHT_CONTROLLER;
				crsfData[1] = 24; 			
				crsfData[2] = SPORT_FRAMETYPE_RC_CHANNELS_PACKED;
		}
		
   
    uint8_t crc = calcCRC(&crsfData[2], crsfData[1] - 1);
		
    crsfData[25] = crc; 
		if(sport_or_crsf_flag)
		{
				if(LL_DMA_IsEnabledChannel(DMA1,LL_DMA_CHANNEL_3))
				{
						LL_DMA_DisableChannel(DMA1,LL_DMA_CHANNEL_3);
						while(LL_DMA_IsEnabledChannel(DMA1,LL_DMA_CHANNEL_3));
				}
				
				LL_DMA_SetMemoryAddress(DMA1, LL_DMA_CHANNEL_3, (uint32_t)crsfData);
				//LL_DMA_SetPeriphAddress(DMA1, LL_DMA_CHANNEL_3, (uint32_t)(&USART2->TDR));
				LL_DMA_SetDataLength(DMA1, UART2_TX_DMA_CHANNEL, 26);
				LL_DMA_EnableChannel(DMA1, UART2_TX_DMA_CHANNEL);
				LL_USART_EnableDMAReq_TX(USART2);
		}else if(!sport_or_crsf_flag){
				if(LL_DMA_IsEnabledChannel(DMA1,LL_DMA_CHANNEL_1))
				{
						LL_DMA_DisableChannel(DMA1,LL_DMA_CHANNEL_1);
						while(LL_DMA_IsEnabledChannel(DMA1,LL_DMA_CHANNEL_1));
				}
				
				LL_DMA_SetMemoryAddress(DMA1, LL_DMA_CHANNEL_1, (uint32_t)crsfData);
				//LL_DMA_SetPeriphAddress(DMA1, LL_DMA_CHANNEL_3, (uint32_t)(&USART2->TDR));
				LL_DMA_SetDataLength(DMA1, UART1_TX_DMA_CHANNEL, 26);
				LL_DMA_EnableChannel(DMA1, UART1_TX_DMA_CHANNEL);
				LL_USART_EnableDMAReq_TX(USART1);
		}
}






